package com.efounder.frame.activity;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.core.content.res.ResourcesCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.frame.activity.helper.EFAppAccountMainActivityHelper;
import com.efounder.frame.activity.manager.EFAppAccountMainActivityFragmentManager;
import com.efounder.frame.baseui.EFActivity;
import com.efounder.frame.fragment.EFAppAccountPagerSlidingTabFragment;
import com.efounder.frame.fragment.EFAppAccountTabFragmentInterface;
import com.efounder.frame.tabbar.EFTabBar;
import com.efounder.frame.tabbar.EFTabBarItem;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.frame.xmlparse.EFAppAccountRegistry;
import com.efounder.frame.xmlparse.EFXmlConstants;
import com.efounder.mobilemanager.R;
import com.efounder.utils.PublicAccoutDown;
import com.efounder.utils.PublicAccoutDownInterface;
import com.efounder.utils.WithProgressLoadingWithUpdate;

import java.io.File;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.List;

/**
 * Created by hudq on 2016/8/16. XX
 * 应用号Activity 再用
 */

public class EFAppAccountMainActivity_old extends EFActivity implements EFTabBar.OnTabBarItemClickListener,
        EFAppAccountPagerSlidingTabFragment.OnViewPagerMeasureCompleteDelegate,
        EFAppAccountMainActivityInterface ,EFAppAccountPagerSlidingTabFragment.EFAppAccountPagerSlidingTabFragmentListener{
    private long systemCurrentTime;

    public static final String TAG = "EFAppAccountMainActivity";
    /**
     * 底部TabBar
     **/
    private EFTabBar efTabBar;
    /**
     * 是否缓存fragment
     **/
    private boolean isCacheFragment = true;
    /**
     * 是否同时初始化所有tab对应的fragment
     **/
    private boolean isInitAllTabFragment = false;
    /**
     * helper只能new一个
     **/
    private EFAppAccountMainActivityHelper mainActivityHelper;
    /**
     * fragmentManager只能new一个
     **/
    private EFAppAccountMainActivityFragmentManager mainActivityFragmentManager;
    /**
     * 初始化的position，这个值可以是配置的
     **/
    private int initPosition = -1;

    private List<StubObject> dataList;

    private ProgressDialog progressDialog;
    private Bundle savedInstanceState;

    private String url;
    private Handler handler  = new MyHandler(this);

    private static class MyHandler extends Handler{
        private WeakReference<EFAppAccountMainActivity_old> activityWeakReference;

        public MyHandler(EFAppAccountMainActivity_old activity) {
            this.activityWeakReference = new WeakReference<EFAppAccountMainActivity_old>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            EFAppAccountMainActivity_old activity = activityWeakReference.get();
            if (activity != null){
                switch (msg.what){
                    case 0:
                        activity.progressDialog.dismiss();
                        activity.downResourse();
                    break;
                    case 1:
                        Toast.makeText(activity,"没有该应用号相关资源",Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        activity.progressDialog.dismiss();
                        activity.beginCreateView(activity.savedInstanceState);
                        break;
                }
            }

        }


    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.w("--", TAG + "-----onCreate--savedInstanceState：" + savedInstanceState);
        this.savedInstanceState = savedInstanceState;
        //XXX-存储全局使用的应用号id
        final int appAccountID = getIntent().getIntExtra("id",0);
        EFAppAccountUtils.saveAppAccountID(appAccountID);
        mainActivityHelper = new EFAppAccountMainActivityHelper();
        mainActivityFragmentManager = new EFAppAccountMainActivityFragmentManager(getSupportFragmentManager());
        //如果被回收后，重新创建
        if (savedInstanceState != null) {
            int currentPosition = savedInstanceState.getInt("currentPosition");
            //给fragmentManager恢复数据
            mainActivityFragmentManager.setCurrentPosition(currentPosition);
        }
        setContentView(R.layout.ef_activity_main);
///==============================================================================================

        progressDialog = ProgressDialog.show(this,"请稍候","正在初始化界面...");
        progressDialog.setCancelable(true);
        new Thread(){
            @Override
            public void run() {
                //FIXME 判断本地应用号资源文件是否存在
                if (new File(EFAppAccountUtils.getAppAccountRootPath()).exists()){
                    //1.初始化注册表
                    mainActivityHelper.initRegistry();
                    //2.初始化数据
                    initData();
                    handler.sendEmptyMessage(2);
                }else {//应用号不存在
                    url = "http://mobile.osp.cloud/ESTMobile/APPS/"+appAccountID+".zip";
                    URL urlLink;
                    try {
                        urlLink = new URL(url);
                        InputStream in = urlLink.openStream();
                        handler.sendEmptyMessage(0);
                        System.out.println("连接可用");
                    } catch (Exception e1) {
                        System.out.println("连接打不开!");
                        handler.sendEmptyMessage(1);
                        urlLink = null;
                    }
                }

            }
        }.start();
    }

    private void beginCreateView(@Nullable Bundle savedInstanceState){

        //3.初始化底部TabBar
        initTabBar(mainActivityHelper, dataList);
        //在efTabBar实例化之后，将efTabBar与mainActivityFragmentManager绑定
        mainActivityFragmentManager.setEfTabBar(efTabBar);
        //4.处理tltleView
        initTitleView(savedInstanceState);
        //如果第一次onCreate，初始化Fragment，fragment与activity绑定之后，fragment会跟随activity生命周期，自动创建
        if (savedInstanceState == null) {
            if (isCacheFragment && isInitAllTabFragment) {//同时初始化所有tab对应的fragment
                mainActivityFragmentManager.initAllTabFragment(dataList, initPosition);
            } else {
                mainActivityFragmentManager.showFragment(initPosition, dataList.get(initPosition), isCacheFragment);
            }
        }
    }

    private void initData() {
        //从注册表中获取数据
        dataList = EFAppAccountRegistry.getStubListByElementName(EFXmlConstants.ELE_MENU_ROOT);
        StubObject mainFrameStub = EFAppAccountRegistry.getStubByID(EFXmlConstants.ID_MAIN_FRAME);
        if (mainFrameStub != null) {
            //isCacheFragment 默认为true
            isCacheFragment = mainFrameStub.getString(EFXmlConstants.ATTR_IS_CACHE_FRAGMENT, "1").equals("1") ? true : false;
            //isInitAllTabFragment 默认为false
            isInitAllTabFragment = mainFrameStub.getString(EFXmlConstants.ATTR_IS_INIT_ALL_TAB_FRAGMENT, "0").equals("1") ? true : false;
            String initPositionStr = mainFrameStub.getString(EFXmlConstants.ATTR_INIT_POSITION, "0");
            try {
                initPosition = Integer.parseInt(initPositionStr);
            } catch (NumberFormatException e) {
                initPosition = 0;
                e.printStackTrace();
            }
        }
    }

    private void initTabBar(EFAppAccountMainActivityHelper mainActivityHelper, List<StubObject> dataList) {
        efTabBar = mainActivityHelper.createTabBar(this, dataList);
        // 2.TabBar添加OnTabClickListener
        efTabBar.setOnTabBarItemClickListener(this);
//        efTabBar.setIndicatorNumber(2,2);
        efTabBar.setIndicatorTextColor(ResourcesCompat.getColor(getResources(),R.color.ef_white,null));
        //旋转屏幕，savedInstanceState != null,showFragment不会调用,需要自己初始化一下位置
        efTabBar.setSelectedTab(mainActivityFragmentManager.getCurrentPosition());
    }

    private void initTitleView(Bundle savedInstanceState) {
        hideEFTitleView();
        //设置允许打开左边抽屉
        initDrawerLayout(savedInstanceState);
    }

    /**
     * 初始化DrawerLayout
     */
    private void initDrawerLayout(Bundle savedInstanceState){
        //设置允许打开左边抽屉
        getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
        if (savedInstanceState == null){
            //TODO 设置左边抽屉Fragment
            try {
                FragmentManager fragmentManager = getSupportFragmentManager();
                Fragment leftFragment = (Fragment) Class.forName("com.efounder.fragment.AppAccountLeftDrawerFragment").newInstance();
                fragmentManager.beginTransaction().replace(getDrawerLayoutLeftLayoutResId(),leftFragment).commit();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.w("--", TAG + "-----onStart--");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.w("--", TAG + "-----onResume--");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.w("--", TAG + "-----onPause--");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.w("--", TAG + "-----onStop--");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EFAppAccountRegistry.clearRegister();
        Log.w("--", TAG + "-----onDestroy--");
        //FIXME 临时处理arcMenu
//        ArcMenuList.arcMenuList.clear();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //被回收时,保存当前位置
        outState.putInt("currentPosition", mainActivityFragmentManager.getCurrentPosition());
    }

    @Override
    public void onTabBarItemClick(EFTabBarItem EFTabBarItem, int position) {
        if (position == mainActivityFragmentManager.getCurrentPosition()) {
            return;
        }
        efTabBar.clearIndicator(position);
        // TODO tabBar点击事件
        mainActivityFragmentManager.showFragment(position, dataList.get(position), isCacheFragment);
    }

    @Override
    public void onViewPagerMeasureComplete(int position) {
        if (isCacheFragment && isInitAllTabFragment) {//同时初始化所有tab对应的fragment
            if (position != mainActivityFragmentManager.getCurrentPosition())
                mainActivityFragmentManager.hideFragment(position);
        }
    }


    @Override
    public void gotoFragment(int tabFragmentPosition, int viewPagerFragmentPosition) {
        EFAppAccountPagerSlidingTabFragment tabFragment = mainActivityFragmentManager.showFragment(tabFragmentPosition, dataList.get(tabFragmentPosition), isCacheFragment);
        if (tabFragment instanceof EFAppAccountTabFragmentInterface) {
            EFAppAccountTabFragmentInterface gotoViewPagerFragmentInterface = tabFragment;
            gotoViewPagerFragmentInterface.gotoViewPagerFragment(viewPagerFragmentPosition);
        }
    }

    @Override
    public void onClickLeftViewListener(View view) {
        getDrawerLayout().openDrawer(Gravity.LEFT);
    }

    @Override
    public void onBackPressed() {
        //拦截返回事件
        if (System.currentTimeMillis() - systemCurrentTime > 3000) {
            Toast.makeText(this, "再按一次退出应用号", Toast.LENGTH_SHORT).show();
            systemCurrentTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    }

    private void downResourse() {

        final PublicAccoutDown publicAccoutDown = new PublicAccoutDown(EFAppAccountMainActivity_old
                .this);

        WithProgressLoadingWithUpdate.show(EFAppAccountMainActivity_old.this);
        WithProgressLoadingWithUpdate.getTitle().setText("中油铁工");
        WithProgressLoadingWithUpdate.getContent().setText("-界面设计优化\n-页面动态加载\n-数据实时变化");
        WithProgressLoadingWithUpdate.getDown().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WithProgressLoadingWithUpdate.getDown().setClickable(false);
                WithProgressLoadingWithUpdate.getDown().setTextColor(Color.parseColor("#A5A5A5"));

                publicAccoutDown.start(url, new PublicAccoutDownInterface() {
                    @Override
                    public void startDown(float DownBeginFromPercent) {

                    }

                    @Override
                    public void updateProgress(float progress) {
                        WithProgressLoadingWithUpdate.getBar().setProgress((int) progress * 100);
                        WithProgressLoadingWithUpdate.getProgresstext().setText((int) progress * 100 + "%");
                    }

                    @Override
                    public void downloadOver(String filePath) {
                        WithProgressLoadingWithUpdate.dismiss();


                        progressDialog = new ProgressDialog(EFAppAccountMainActivity_old.this);
                        progressDialog.setMessage("正在解压...");
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        progressDialog.show();

                        String fileName = url.substring(url.lastIndexOf("/") + 1);
                        publicAccoutDown.unzipAndEncryptFile(filePath, EFAppAccountUtils.getAppAccountAppsPath() + "/" +
                                fileName);
                    }

                    @Override
                    public void error() {
                        WithProgressLoadingWithUpdate.dismiss();
                        Toast.makeText(EFAppAccountMainActivity_old.this, "下载应用号资源失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void stop() {

                    }

                    @Override
                    public void unZIPOVER() {

                        progressDialog.dismiss();
                        System.out.println("-------------下载并解压完成-----------------");
                        //1.初始化注册表
                        mainActivityHelper.initRegistry();
                        //2.初始化数据
                        initData();
                        handler.sendEmptyMessage(2);

                    }
                });

            }
        });
        WithProgressLoadingWithUpdate.getCancle().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WithProgressLoadingWithUpdate.dismiss();
            }
        });


    }
}
